package cn.shujuhai.qtadmin.platform.pluging.security;

import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.jetbrains.annotations.NotNull;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 动态获取用户访问规则
 *
 * @author dch798
 * @date 2021/08/27 19:19
 **/
@Slf4j
@Component("myRBACService")
public class MyRbacService {
    public boolean hasPermission(@NotNull HttpServletRequest request, @NotNull Authentication auth) {
        if (CharSequenceUtil.contains(request.getRequestURI(), "error")) {
            return true;
        }
        if (auth.getPrincipal() instanceof UserDetails) {
            var authorities = ((UserDetails)auth.getPrincipal()).getAuthorities();
            var matchs = authorities.stream().filter(s -> CharSequenceUtil.contains(s.getAuthority(), "*")
                || CharSequenceUtil.contains(s.getAuthority(), "?")).collect(Collectors.toList());
            log.info(request.getRequestURI() + "==================================");
            if (ObjectUtil.isNotEmpty(matchs)) {
                AntPathMatcher antPathMatcher = new AntPathMatcher();
                for (GrantedAuthority grantedAuthority : matchs) {
                    if (antPathMatcher.match(grantedAuthority.getAuthority(), request.getRequestURI())) {
                        return true;
                    }
                }
            }
            return authorities.contains(new SimpleGrantedAuthority(request.getRequestURI()));
        }
        return false;
    }
}
